package test

import (
	"lark/consts"
	"lark/proto"
	"net"
	"time"

	"fmt"
	"github.com/dchest/uniuri"
	"github.com/magiconair/properties/assert"
	"testing"
)

func requestOnce(t *testing.T, network string, addr string) {
	conn, err := net.Dial(network, addr)
	panicErr(err)

	p := proto.NewlarkProtoV2(conn, time.Second, time.Second)
	defer p.Close()

	code := uniuri.New()
	err = p.Write(consts.Lc2lcpTagTaskReq, []byte(code), []byte(serviceName))
	if err != nil {
		panicErr(err)
		return
	}

	tag, payload, err := p.Read()
	if err != nil {
		panicErr(err)
		return
	}

	if tag != consts.Lcp2lcTaskRespOK {
		panicErr(fmt.Errorf("wrong tag. %d", tag))
		return
	}

	assert.Equal(t, proto.SplitPayload(payload)[0], []byte(code))
}

func requestJmtextOnce(t *testing.T, network, addr string) {
	conn, err := net.Dial(network, addr)
	panicErr(err)

	code := uniuri.New()
	content := []byte("3\nRPC\n16\n" + code)
	_, err = conn.Write(content)
	panicErr(err)

	var retBuf = make([]byte, len(content))
	conn.SetReadDeadline(time.Now().Add(time.Second))
	_, err = conn.Read(retBuf)
	panicErr(err)

	assert.Equal(t, content, retBuf)
}
